package jun.home.dailycost.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import jun.home.dailycost.domain.Category;
import jun.home.dailycost.domain.Item;
import jun.home.dailycost.service.CategoryService;
import jun.home.dailycost.service.ItemService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/item")
public class ItemController {
	
	private ItemService itemService;
	private CategoryService categoryService;
	private Validator itemValidator;
	
	@Autowired
	public void setItemService(ItemService itemService) {
		this.itemService = itemService;
	}
	
	@Autowired
	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}
	
	@Autowired
	public void setValidator(Validator itemValidator) {
		if (itemValidator.supports(Item.class))
		this.itemValidator = itemValidator;
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		CategoryEditor catEditor = new CategoryEditor();
		catEditor.setCategoryService(categoryService);
		binder.registerCustomEditor(Category.class, "cat", catEditor);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, "date", new CustomDateEditor(dateFormat, true));
	}
	
	@ModelAttribute("catList")
	public List<Category> populateCategoryList() {
		return categoryService.selectAll();
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(
			@RequestParam(required = false, value = "id") Integer id,
			Model model) {
		Item item = null;
		if (id == null) { // create new form
			item = new Item();
		} else {
			int idInt = id.intValue();
			item = itemService.selectItem(idInt);
		}
		model.addAttribute("item", item);
		return "item";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String submitForm(
			@ModelAttribute("item") Item item,
			BindingResult result,
			HttpServletRequest request) {
		if (request.getParameter("cancel") != null) {
			return "redirect:itemList.html";
		} else {
			itemValidator.validate(item, result);
			if (result.hasErrors()) {
				return "item";
			} else {
				itemService.storeItem(item);
				return "redirect:itemList.html";
			}
		}
	}

}
